import { deviceDetection } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import {  FormItemProps } from "./types";
import { useStyleHooks } from "@/views/hooks/style";
import { usePublicHooks } from "@/views/hooks/public";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import { getDictPagedList, createDict, updateDict, deleteDict } from "@/api/sys/dict";
import editForm from "../form.vue";

export function useDict() {
  const { tagStyle } = useStyleHooks();
  const { getPageQueryParams } = usePublicHooks();

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
   });
  
  const columns: TableColumnList = [
    {
      label: "字典名称",
      prop: "name",
      width: 120,
    },
    {
      label: "字典代码",
      prop: "code",
      width: 120,
    },
    {
      label: "状态",
      prop: "status",
      width: 80,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "备注",
      prop: "remark",
    },
    {
      label: "操作",
      fixed: "right",
      width: 80,
      slot: "operation"
    }
  ];

  async function onSearch() {
    loading.value = true;
    const params = getPageQueryParams(pagination);
    const { data } = await getDictPagedList(params);
    dataList.value = data.items;
    pagination.total = data.totalCount;

    loading.value = false;
  }

  function openDialog(mode = "add", row?: FormItemProps) {
    addDialog({
      title: "",
      props: {
        formInline: {
          id: row?.id ?? 0,
          name: row?.name ?? "",
          code: row?.code ?? "",
          isPrimitive: row?.isPrimitive ?? false,
          status: row?.status ?? 1,
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async (valid: any) => {
          if (valid) {
            if (mode === "add") {
              const ret = await createDict(curData);
              if (!ret.success) {
                message(`新增字典失败，${ret.message}`, { type: "warning" });
                return;
              }
            } else {
              const ret = await updateDict(curData);
              if (!ret.success) {
                message(`编辑字典失败，${ret.message}`, { type: "warning" });
                return;
              }
            }
            chores();
          }
        });
      }
    });
  }

  /** 新增字典 */
  const handleAdd = () => {
    openDialog("add");
  };

  /** 编辑字典 */
  const handleEdit = (row: FormItemProps) => {
    openDialog("edit", row);
  };

  /** 删除字典 */
  const handleDelete = async (row: FormItemProps) => {
    const ret = await deleteDict(row.id);
    if (!ret.success) {
      message(`删除字典失败，${ret.message}`, { type: "warning" });
      return;
    }
    onSearch();
  };

  function handleChangeCurrentPage(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleChangePageSize(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    loading,
    pagination,
    columns,
    dataList,
    onSearch,
    handleAdd,
    handleEdit,
    handleDelete,
    handleChangeCurrentPage,
    handleChangePageSize,
  };
}
